package com.paishen.libalipay;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.util.Random;


public class PayManager {
    // 商户PID
    public static final String PARTNER = "2088611939371266";
    // 商户收款账号
    public static final String SELLER = "echobi@bzihao.com";
    // 商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALG3vMhpvBus33N999i99ki48EM120WoZlrMVs1McV7Gt+PtWExnNYb7E0illQbQqpoktnD/+r+4RgjPTJy1O4bmcG2MeWwj+DwvDZeE1giGE0PICcUNkuTKPQvyTfPQao5GtqYhyF3hzDJ1tOwDyLPzyV4uEKs3aIfTQlmKRrwTAgMBAAECgYByTpTtbxzfzCR5W3eUADMt+U4IXNapijQziKT4LYfqBvT2dI3LrsK+DDYODvq4xHRG6wAx1GPK9tKNDhDf5q3e9yki7XPyev39awvKHoMZoThevrPL2v1C2jgDfl+otYKdu2dw9bZ1PYyUUsEwzRiVH/TRX32OI6vMjHGXZBAuMQJBAN7QHR3/UPEVUm6hwSeytM3UUPI8W6TQY/n7DCYiccMimvIh8/ZatbkRZQHlkOU1qi8wWd670pj82AnMsDtTUvkCQQDMMCMcQomjg/g3s7e9yMH/3Cz3cbRPbAqMgDng4mlYbYRvaSrx2kl2AtxfOyy0+pI+7Dj66mL/26rg3uELIP5rAkBroYiPNwg4jR42xvhxXsgsLYW0nid+5BOHbBggS788jfjfQjuBI6xo69gpJGXr8xJ0nRyslXpT4L/TbActgUCxAkAjmvFEaEXgAY8zB1+u9Gb/2sDslSNABjMAtQtir5h3FwHU+53Fdq8AqRcMdCEjnd4Kot58wopo20E83SCY9DPpAkEAkW/3P3I//8H2MSKnzHQ03LmkfCgS3wG50hThq+/h3juUZEnYLEaM/adlaHJlWIzcqbpZkS8dyOFgCTpBYmSZTQ==";
    // 支付宝公钥
    // public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    public interface PayResultListener {
        void onSuccess();

        void onDealing();

        void onFail();
    }

    static class PayHandler extends Handler {
        /**
         * don't change value
         */
        static final String RESULT_STATUS_SUCCESS = "9000";
        static final String RESULT_STATUS_DEALING = "8000";
        static final String RESULT_STATUS_FAIL = "4000";
        static final String RESULT_STATUS_CANCEL = "6001";
        static final String RESULT_STATUS_NET_ERROR = "6002";

        private final WeakReference<Activity> mWRActivity;
        private final PayResultListener callback;

        public PayHandler(Activity activity, PayResultListener listener) {
            mWRActivity = new WeakReference<>(activity);
            callback = listener;
        }


        @Override
        public void handleMessage(Message msg) {
            Activity activity = mWRActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case SDK_PAY_FLAG: {
                        PayResult payResult = new PayResult((String) msg.obj);

                        // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                        String resultInfo = payResult.getResult();

                        String resultStatus = payResult.getResultStatus();

                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, RESULT_STATUS_SUCCESS)) {
                            Toast.makeText(activity.getApplicationContext(), "支付成功", Toast.LENGTH_SHORT).show();
                            if (callback != null) callback.onSuccess();
                        } else {
                            // 判断resultStatus 为非“9000”则代表可能支付失败
                            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            if (TextUtils.equals(resultStatus, RESULT_STATUS_DEALING)) {
                                Toast.makeText(activity.getApplicationContext(), "支付结果确认中", Toast.LENGTH_SHORT).show();
                                if (callback != null) callback.onDealing();
                            } else {
                                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                                Toast.makeText(activity.getApplicationContext(), "支付失败", Toast.LENGTH_SHORT).show();
                                if (callback != null) callback.onFail();
                            }
                        }
                        break;
                    }
                    case SDK_CHECK_FLAG: {
                        Toast.makeText(activity.getApplicationContext(), "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                        break;
                    }
                }
            }
        }
    }

    /**
     * test call alipay sdk pay. 调用SDK支付
     */
    public static void pay(final Activity context, String tradeNo, float price, String orderName, String orderDescription, String URL_SERVICE_PAY_NOTIFY, PayResultListener callback) {
        String notifyUrl = URL_SERVICE_PAY_NOTIFY;
        pay(context, orderName, orderDescription, price, tradeNo, notifyUrl, callback);
    }

    /**
     * call alipay sdk pay. 调用SDK支付
     *
     * @param subject   商品名称
     * @param body      商品详情
     * @param coin      商品价格
     * @param tradeNo   商户网站唯一订单号
     * @param notifyUrl 服务器异步通知页面路径
     */
    private static void pay(final Activity context, String subject, String body, float coin, String tradeNo, String notifyUrl, PayResultListener callback) {
        if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE)
                || TextUtils.isEmpty(SELLER)) {
            Log.e("PayManager", "empty pay params [PARTNER|RSA_PRIVATE|SELLER]");
            return;
        }

        // 订单
        String orderInfo = getOrderInfo(subject, body, String.valueOf(coin), tradeNo, notifyUrl);
        // 对订单做RSA 签名
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

        final PayHandler mDelivery = new PayHandler(context, callback);
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(context);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mDelivery.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * check whether the device has authentication alipay account.
     * 查询终端设备是否存在支付宝认证账户
     */
    public static void check(final Activity context, PayResultListener callback) {
        final PayHandler mDelivery = new PayHandler(context, callback);
        Runnable checkRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask payTask = new PayTask(context);
                // 调用查询接口，获取查询结果
                boolean isExist = payTask.checkAccountIfExist();

                Message msg = new Message();
                msg.what = SDK_CHECK_FLAG;
                msg.obj = isExist;
                mDelivery.sendMessage(msg);
            }
        };

        Thread checkThread = new Thread(checkRunnable);
        checkThread.start();
    }

    /**
     * get the sdk version. 获取SDK版本号
     */
    public static void getSDKVersion(Activity context) {
        PayTask payTask = new PayTask(context);
        String version = payTask.getVersion();
        Toast.makeText(context.getApplicationContext(), version, Toast.LENGTH_SHORT).show();
    }

    /**
     * create the order info. 创建订单信息
     */
    private static String getOrderInfo(String subject, String body, String price, String tradeNo, String notifyUrl) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + tradeNo + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + notifyUrl + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

//        /**
//         * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
//         */
//        private static String getOutTradeNo() {
//            SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
//                    Locale.getDefault());
//            Date date = new Date();
//            String key = format.format(date);
//
//            Random r = new Random();
//            key = key + r.nextInt();
//            key = key.substring(0, 15);
//            return key;
//        }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    private static final String sign(String content) {
        return SignUtils.sign(content, RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    private static final String getSignType() {
        return "sign_type=\"RSA\"";
    }

}
